<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<jsp:include page="common/auth.jsp" />
<jsp:include page="common/header.jsp" />
<body>
  <jsp:include page="common/topmenu-owner.jsp" />

<%@ page language="java" import="java.sql.*" %>
<%@ page language="java" import="java.util.ArrayList" %>
<%@ page language="java" import="db.Config" %>
<%-- -------- Open Connection Code -------- --%>

<%
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;

	try {
    // Load JDBC Driver class file
    Class.forName(Config.jdbcDriver);

    // Open a connection to the database using DriverManager
    conn = DriverManager.getConnection(Config.connectionURL, Config.username, Config.password);

%>

  <div class="container-fluid">
  	<div class="row-fluid">
      <table class="table table-hover table-condensed" id="dashboard">
        <tr id="state">
          <th></th>
        <%
          int size = Config.states.length;
          for(int i = 0; i < size; ++i){
        %>
          <th id="state"><%= Config.states[i]%></th>                           
        <%
          }
        %>
        </tr>
        <%
          pstmt = conn.prepareStatement("SELECT name FROM category ORDER BY name");
          rs = pstmt.executeQuery();
          while (rs.next()) {
        %>
        <tr id="<%= rs.getString("name") %>">
          <th><%= rs.getString("name") %></th>
        <%
          for(int i = 0; i < size; ++i){
        %>
          <td id="<%= rs.getString("name") + "-" + Config.states[i] %>"></td>                           
        <%
          }
        %>
        </tr>
        <%
          }
        %>
      </table>
	  </div>
  </div>

<%-- -------- Close Connection Code -------- --%>
<%
  // Close the ResultSet
  //rs.close();

  // Close the Statement
  //pstmt.close();

  // Close the Connection
  conn.close();
} catch (SQLException e) {
  
  // Wrap the SQL exception in a runtime exception to propagate
  // it upwards
  String errorMsg = e.getMessage();
  //TODO: Parse error message to display user-friendly messages.
%>
  <!-- Display error message -->
  <div class="container">
    <div class="alert alert-error">
      <button type="button" class="close" onclick="window.location.href='categories.jsp'">&times;</button>
      <strong>Error!</strong> <%= errorMsg %>
    </div>
  </div>
<%
}
finally {
  // Release resources in a finally block in reverse-order of
  // their creation

  if (rs != null) {
    try {
      rs.close();
    } catch (SQLException e) { } // Ignore
    rs = null;
  }
  if (pstmt != null) {
    try {
      pstmt.close();
    } catch (SQLException e) { } // Ignore
    pstmt = null;
  }
  if (conn != null) {
    try {
      conn.close();
    } catch (SQLException e) { } // Ignore
    conn = null;
    }
  }
	
%>
  <script src="js/jquery-1.9.1.js"></script>
  <script src="js/bootstrap.min.js"></script>
  <script>

    $(document).ready(function() {
      $('#nav-dashboard').addClass('active');

      var uuid = 
        'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });

      var updateList = [];

      initRequest(uuid);

      setInterval(function(){update(uuid, updateList)}, 2000);
    });

    function generateUUID() {
      return
        'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
          var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
            return v.toString(16);
        });
    }

    function initRequest(uuid) {
      $.getJSON('dashboard_ajax.jsp?uuid=' + uuid + '&action=initRequest', function(data) {

        for (var i = 0; i < data.length; i++) {
          $('#' + data[i].category + '-' + data[i].state).text(data[i].sales);
        }
      });
    }

    function update(uuid, updateList) {
      $.getJSON('dashboard_ajax.jsp?uuid=' + uuid + '&action=update', function(data) {

        for (var i = 0; i < updateList.length; i++) {
          $('#' + updateList[i]).removeClass('alert-info');
        }
        updateList = [];

        for (var i = 0; i < data.length; i++) {
          var cell = $('#' + data[i].category + '-' + data[i].state); 
          if (cell.length > 0) {
            updateCell(cell, data[i].sales);
            updateList.push(data[i].category + '-' + data[i].state);
          } else {
            // new category
            if (data[i].state == 'newCategory') {
              addCategory(data[i].category);
            } else if (data[i].state = 'removeCategory') {
              removeCategory(data[i].category);
            } else {
              addCategory(data[i].category);
              updateCell(cell, data[i].sales);
              updateList.push(data[i].category + '-' + data[i].state);
            }
          }
        }
      });
    };

    function updateCell(cell, newData) {
      var oldSales = parseInt(cell.text()) || 0;
      var updates = parseInt(newData) || 0;
      cell.text(oldSales + updates);
      cell.addClass('alert-info');
    }

    function addCategory(category) {
      var stateName = $('#state th');

      var rowHTML = '<tr id="' + category + '"><th>' + category + '</th>';
      for (var i = 0; i < 50; i++) {
        rowHTML += ('<td id="' + category + '-' + stateName[i+1].innerHTML + '"></td>');
      }
      rowHTML += '</tr>'
        
      $('#dashboard tr:last').after(rowHTML);
    }

    function removeCategory(category) {
      $('#' + category).remove();
    }
  </script>
</body>
</html>
